package controller;

import com.alibaba.dubbo.config.annotation.Reference;
import entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: lagou-dubbo
 * @Author: GuoAn.Sun
 * @CreateTime: 2020-07-27 18:16
 * @Description: 控制层
 */
@Controller
@RequestMapping("/user")
public class UserAction {

    @Reference
    private UserService userService;

    @RequestMapping("/save")
    public String register( Users user) {
        System.out.println("来注册");
        System.out.println(user);
        try {
            String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            user.setCreatetime(nowTime);
            userService.register(user);
            return "redirect:/user/findall";
        } catch (Exception e) {
            e.printStackTrace();
            return "失败";
        }
    }

    @RequestMapping("/findall")
    public String findAll(Model model)
    {
        List<Users> userList=userService.selectAll();
        model.addAttribute("userList",userList);
        return "userList";
    }
    @RequestMapping("/update")
    public String update( Users user)
    {
        int res=userService.update(user);
        if(res!=0)
        {
            return "redirect:/user/findall";
        }
        else
        {
            return "update fail";
        }
    }

    @RequestMapping("/delete")
    public String delete(Integer uid)
    {
        userService.delete(uid);
        return "redirect:/user/findall";
    }

    @RequestMapping("/deleteBatch")
    public String deleteBatch(Integer[] ids){
        userService.deleteBatch(ids);
        return "redirect:/user/findall";
    }
    @RequestMapping("/findById")
    @ResponseBody
    public List<Users> findById(Integer uid)
    {

        Users user= userService.selectById(uid);
        List<Users> users=new ArrayList<>();
        users.add(user);
        return users;
    }

    @RequestMapping("/selectbynameandphone")
    public String selectbynameandphone(@RequestParam("username") String username,@RequestParam("phone") String phone ,Model model){
        List<Users> userList=userService.selectByLike(username,phone);
        model.addAttribute("userList",userList);
        System.out.println(userList);
        return "userList";

    }
}
